/**
 * @description global utils
 * @example this.$utils.customFunction(params)
 * @author Zhangbin
 */

import { App } from 'vue'
import download from 'downloadjs'
import moment, { Moment } from "moment"

// option type
interface OptionsTypes {
  version: string
}

export default {
  install(app: App, options: OptionsTypes): void {
    const proxy = app.config.globalProperties;
    const { $router, $store, $message } = proxy;

    class Properties {
      constructor() { }

      /**
       * @description is true
       * @param {params} any
       */
      public $isTrue = (v: any): boolean => {
        return v !== '' && v !== undefined && v !== null
      }

      /**
       * @description is defined
       * @param {params} any
       */
      public $isDef = (v: any): boolean => {
        return v !== undefined && v !== null
      }

      /**
       * @description has own property
       * @param {obj} object
       * @param {key} string
       */
      public $hasOwn = (obj: object, key: string): boolean => {
        const hasOwnProperty = Object.prototype.hasOwnProperty;
        return hasOwnProperty.call(obj, key)
      }

      /**
       * @description download file
       * @param {url} string
       */
      public $download = (url: string, name?: string, type?: string): void => {
        try {
          download(url, name, type);
          $message.success('download success!!')
        } catch (error) {
          $message.error('download fail!!')
        }
      }

      /**
       * @description format request date params
       * @param {date} array
       * @param {key} string
       */
      public $formatReqDate = (
        date: { [key: string]: any }, key: string = 'YYYY-MM-DD'
      ): object | undefined => {
        let startDate = date?.[0]?.['_d'] || '',
          endDate = date?.[1]?.['_d'] || '';

        if (!this.$isTrue(startDate) || !this.$isTrue(endDate)) {
          return {
            startDate, endDate
          }
        }

        try {
          startDate = moment(startDate).format(key);
          endDate = moment(endDate).format(key);
          return {
            startDate, endDate
          }
        } catch (error) {
          this.#_error('$formatReqDate')
        }
      }
      /**
       * @description error log
       * @param {funcName} string
       */
      #_error = (funcName: string = ''): void => {
        console.error(`[Error] Global Api $utils: Something went wrong during ${funcName} was called.`)
      }
    }

    const Instance = new Properties();
    app.config.globalProperties.$utils = Instance
  }
}